<template>
  <BaseMainSlot :show-btn-box="false">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="29"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-cancel="false"
        :has-save="false"
        :has-add="true"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">投料设备名称:</div>
          <div class="input">
            <el-input
              v-model="queryList.deviceName"
              clearable
              placeholder="请输入任务名称"
            />
          </div>
        </div>
        <!-- <div class="common-search-item">
          <div class="label">投料车名称:</div>
          <div class="input">
            <el-select v-model="queryList.facilityNo" clearable>
              <el-option
                v-for="item in facilityList"
                :key="item.facilityNo"
                :label="item.facilityName"
                :value="item.facilityNo"
              />
            </el-select>
          </div>
        </div>-->
        <div class="common-search-items">
          <div class="label">选择时间:</div>
          <div class="input date" clearable>
            <el-date-picker
              v-model="queryList.issueTime"
              type="date"
              value-format="yyyy-MM-dd 00:00:00"
              placeholder="请选择开始时间"
              :picker-options="startDatePicker"
              clearable
            />
            <span class="date-ps">-</span>
            <el-date-picker
              v-model="queryList.completeTime"
              type="date"
              value-format="yyyy-MM-dd 23:23:59"
              placeholder="请选择结束时间"
              :picker-options="endDatePicker"
              clearable
            />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="multiTable"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <!-- <el-table-column prop="batchName" label="任务名称" /> -->
        <el-table-column prop="deviceName" label="投料设备" />
        <el-table-column prop="startRfid" label="开始点" min-width="160" />
        <el-table-column prop="endRfid" label="结束点" min-width="160" />
        <el-table-column prop label="投料量">
          <template
            v-if="tableScope.row.taskId"
            slot-scope="tableScope"
          >{{ tableScope.row.amount+'kg' }}</template>
        </el-table-column>
        <!-- <el-table-column prop="batchNo" label="投料时间" min-width="160" /> -->
        <el-table-column prop="issueTime" label="下发时间" min-width="160" />
        <el-table-column prop="completeTime" label="完成时间" min-width="160" />
        <!-- <el-table-column min-width="160" label="操作">
          <template v-if="scope.row.taskId" slot-scope="scope">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="add(scope.row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="del(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>-->
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '投料任务'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="68%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            label="任务名称:"
            prop="agriculturalWorkTypeName"
            class="w50p"
          >
            <el-input
              v-model="formData.agriculturalWorkTypeName"
              placeholder="请输入任务名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="投料设备:" prop="workload" class="w50p">
            <el-select
              v-model="formData.workloadUnitNo"
              placeholder="请输选择投料设备"
              clearable
            >
              <el-option
                v-for="item in unitlist"
                :key="item.unitNo"
                :label="item.unitName"
                :value="item.unitNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开始点:" class="w50p" prop="execStartTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              value-format="timestamp"
              placeholder="请选择开始时间"
            />
          </el-form-item>
          <el-form-item label="结束点:" class="w50p" prop="execEndTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              value-format="timestamp"
              placeholder="请选择结束时间"
            />
          </el-form-item>
          <el-form-item
            label="投料量:"
            prop="agriculturalWorkTypeName"
            class="w50p"
          >
            <el-input
              v-model="formData.agriculturalWorkTypeName"
              style="width: 70%"
              placeholder="请输入投料量"
              clearable
            />
            <el-select
              v-model="formData.workloadUnitNo"
              style="width:30%"
              placeholder="单位"
              clearable
            >
              <el-option
                v-for="item in unitlist"
                :key="item.unitNo"
                :label="item.unitName"
                :value="item.unitNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="投料时间:" class="w50p" prop="execEndTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              value-format="timestamp"
              placeholder="请选择结束时间"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar/index1.vue";
import Pagination from "@/components/Pagination";
import agriculturalRecords from "@/api/digital-production/feedingtruck-task-manage/feeding-task-manage";
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import nowstaff from "@/api/digital-operation/personnel-cost-mansge/staff-manage/index";
import danwei from "@/api/basic-info-manage/unit-manage/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixin";
import moment from "moment";
import SearchBox from "@/components/SearchBox";
import { mapGetters } from "vuex";
export default {
  name: "AgriculturalRecordsManagement",
  components: { Pagination, BaseMainSlot, ActionBar, SearchBox },
  mixins: [mymixin],
  data() {
    return {
      queryList: {
        deviceName: "",
        completeTime: "",
        issueTime: ""
      },
      agriculturalWorkType: {},
      batchList: [],
      // 设施
      facilityList: [],
      facilityAList: [],
      // 限制结束时间不能低于开始时间
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      method: "",
      unitlist: [],
      personNo: "",
      staffList: [],
      rules: {
        agriculturalWorkTypeName: [
          { required: true, message: "请输入农事作业类型", trigger: "blur" }
        ],
        workload: [
          { required: true, message: "请输入作业量", trigger: "blur" }
        ],
        noticeTime: [
          { required: true, message: "请选择通知时间", trigger: "change" }
        ],
        execStartTime: [
          { required: true, message: "请选择执行开始时间", trigger: "change" }
        ],
        execEndTime: [
          { required: true, message: "请选择执行结束时间", trigger: "change" }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  mounted() {
    // 获取表格数据
    this.getTableDataList();
    this.getqueryAllList();
    this.getStaffList();
    // this.
  },
  methods: {
    getStaffList(no) {
      managementtwo.getEmployeeList(no).then(res => {
        if (res.code !== 1) {
          return;
        }
        this.staffList = res.data;
      });
    },
    getTableDataList() {
      // this.tableData = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.queryList
        }
      };
      agriculturalRecords.getlist(params).then(res => {
        this.loading = false;
        let data = res.data;
        this.totalSize = data.totalElements;
        this.tableData = data.content;
        this.addblankmet();
        this.resetActionBar();
        // this.$refs.formData.resetFields();
      });
    },
    getqueryAllList() {
      // 获取单位选择框数据
      danwei
        .getallunitlist({
          unitTypeNo: "995416636939862016",
          organizationNo: sessionStorage.organizationNo
        })
        .then(res => {
          this.unitlist = res.data;
        });
      danwei
        .getallunitlist({
          unitTypeNo: "1001491616960118784",
          organizationNo: sessionStorage.organizationNo
        })
        .then(res => {
          this.unitlists = res.data;
        });
      nowstaff.getStaffListByCondition().then(res => {
        this.StaffList = res.data;
      });
    },
    // 时间格式
    dateFormat(row, colnum) {
      if (this.formData.agriculturalTaskId) {
        return moment(row[colnum.property]).format("YYYY-MM-DD");
      }
    },
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.queryList.completeTime) {
            //  如果结束时间不为空，则小于结束时间
            return (
              new Date(self.queryList.completeTime).getTime() < time.getTime()
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.queryList.issueTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            return (
              new Date(self.queryList.issueTime).getTime() > time.getTime()
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    add() {
      this.openDialog("add");
      this.formData = {
        agriculturalWorkTypeName: null
      };
    },
    handleSelectionChange(list) {
      this.agriculturalTaskIdList = [];
      this.agriculturalTaskIdList = list.map(item => item.agriculturalTaskId);
      if (this.agriculturalTaskIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    cancel(formData) {
      this.formData = {};
      this.closeDialog();
      if (formData) {
        // this.$refs[formData].resetFields();
      }
    },
    delmessage() {
      if (this.nowChanceStau === "del") {
        let params = {
          agriculturalTaskIdList: this.agriculturalTaskIdList
        };
        agriculturalRecords.delmeslist(params).then(res => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
        });
      }
    },
    handleDelete(data) {
      let params = {
        noList: [data.taskId]
      };
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          agriculturalRecords.delmeslist(params).then(res => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "add") {
            let parone = {
              ...this.formData,
              organizationNo: sessionStorage.getItem("organizationNo"),
              personNoList: this.formData.personList.map(item => item.personNo),
              productionBatchBOList: this.productionBatchBOList
            };
            agriculturalRecords.addmeslist(parone).then(res => {
              if (res.code === 1) {
                this.method = "";
                this.batchNo = "";
                this.getTableDataList();
                this.closeDialog();
                this.$message.success("添加成功");
              } else {
                this.$message.error("添加失败");
              }
            });
          }
          if (this.nowChanceStau === "edit") {
            let params = this.formData;
            this.formData.personNoList = this.formData.personList.map(
              item => item.personNo
            );
            agriculturalRecords.editmeslist(params).then(res => {
              if (res.code === 1) {
                this.method = "";
                this.batchNo = "";
                this.getTableDataList();
                this.closeDialog();
                this.$message.success("修改成功");
              } else {
                this.$message.error("修改失败");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
</style>

